import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'package:flutter/material.dart' hide Action;

Effect<CheckListViewState> buildEffect() {
  return combineEffects(<Object, Effect<CheckListViewState>>{
    CheckListViewAction.action: _onAction,
    Lifecycle.initState: _initState,
    Lifecycle.dispose: _dispose,
    CheckListViewAction.onLoad: _onLoad,
    CheckListViewAction.onTapSort: _onTapSort,
  });
}

void _onAction(Action action, Context<CheckListViewState> ctx) {}

var handle;
String _currentStatus;

void _initState(Action action, Context<CheckListViewState> ctx) {
  handle = (_) {
    ctx.dispatch(CheckListViewActionCreator.setSort(ctx.state.checkStatus));
  };

  bus.on('refreshList', handle);
}

void _dispose(Action action, Context<CheckListViewState> ctx) {
  bus.off('refreshList', handle);
}

void _onLoad(Action action, Context<CheckListViewState> ctx) async {
  await _sendRequest(ctx, action.payload['page'], action.payload['tag']);
}

void _onTapSort(Action action, Context<CheckListViewState> ctx) async {
  ctx.state.checkStatus = action.payload;
  TabController controller =
      DefaultTabController.of(ctx.state.scaffoldKey.currentContext);
  controller.index = 0;
  ctx.dispatch(CheckListViewActionCreator.setSort(action.payload));
}

_sendRequest(Context<CheckListViewState> ctx, int page, String status) async {
  _currentStatus = status;
  String indoorStatus, resultStatus, orderStatus;

  if (ctx.state.checkStatus == 1) {
    orderStatus = '10';
    if (status != '0') {
      indoorStatus = status;
      if (status == '4') {
        orderStatus = '2';
        indoorStatus = '4';
      }
    }
  } else {
    orderStatus = '3';
    if (status != '0') resultStatus = status;
  }
  ResultData res = await CommonNetWork.checkList(
    ctx.state.itemID,
    ctx.state.planID,
    page: page,
    waitCheck: orderStatus,
    indoorStatus: indoorStatus,
    checkStatus: resultStatus,
  );
  if (res.success) {
    List list = res.data['data'];
    List items = list
        .map((e) => CheckListItemModel.fromJson(
              e,
              ctx.state.itemID,
              ctx.state.title,
            ))
        .toList();
    ctx.dispatch(CheckListViewActionCreator.onGetData(items, page, status));
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
    ctx.dispatch(CheckListViewActionCreator.onGetData([], page, status));
  }
}
